<?php

class Template {

	var $tplpath = '';
	var $data = array();
	var $dirs = '';
	var $html = false;
	
    function __construct($tpldir='')
    {
		if($tpldir!=''){
			$this->tplpath = $tpldir;
		}else{
			$this->tplpath = APPTPL;
		}
		$tag_cnf = APPDATA.'cnf/tpl_tag.php';
		if(is_file($tag_cnf)) $this->tpl_tag_cnf = include $tag_cnf;
    }
	
	public function display($view='',$html=false){
		global $application,$sysdata;
		if(!$view){
			$view = str_replace(rtrim(APPPATH,'/'),'',dirname($_SERVER['SCRIPT_FILENAME'])).'/';
			if($view=='/'&&$application->action!='') $view = $application->action.'/';
			$view .= $application->method.'.'.$sysdata['tpl_ext']; 
		}
		if(empty($view)){return false;} 
		$url = $_SERVER['PHP_SELF']; 
		$filename = substr( $url , strrpos($url , '/')+1 ); 
		$view = $this->tplpath.$view;
		//_e($view); 
		if (!file_exists($view)){
			echo ('no tpl!');
			return false;
		}

		preg_match_all ('/<{include file="(.*?)"}>/',file_get_contents($view),$out);
		if(count($out[0])>0){
			foreach($out[1] as $kv=>$v){
				$this->_tag_replace($this->tplpath.$v);
			}
		}
		
		$patterns[] = '/<{include file="(.*?)"}>/';
		$replacements[] = '<?php include("'.APPDATA.'cache/tpl/$1"); ?>';
		
		$tpl_tag = new tpl_tag($application->db);
		if(!empty($this->data)){
			foreach ($this->data as $kv=>$val)
			{
				$$kv = $val;
			}
		}
		$view_path = $this->_tag_replace($view);
		//_e($view_path);
		if($this->html==true) ob_start();
		include($view_path);		
		if ($this->html==true)
		{
			$buffer = ob_get_contents();
			@ob_end_clean();
			return $buffer;
		}
	}
	private function _tag_replace($filename){
		$cachefilename = md5($filename);
		$newfilename = APPDATA.'cache/tpl/'.$cachefilename.".php";
		if (file_exists($newfilename)) {
		
			if(filemtime($filename) > filemtime($newfilename)){
				return $this->_create_cache($filename,$newfilename);
			}else{
				return $newfilename; 
			}
			
		}else{
		
			return $this->_create_cache($filename,$newfilename);
		}
	}
	private function _create_cache($filename,$newfilename){

		$handle = fopen ($filename, "r");
		$contents = fread ($handle, filesize ($filename));
		fclose ($handle);
		$beforestr = array();
		$afterstr = array();

		$patterns[] = '/<glist name="(.*)" id="(.*)" key="(.*)">/U';
		$patterns[] = '/<glist name="(.*)" id="(.*)">/U';
		$patterns[] = "/<\/glist>/";
		$patterns[] = "/<{if(\(.*?\))}>/U";
		$patterns[] = "/<{elseif(\(.*\))}>/U";
		$patterns[] = "/<{else}>/";
		$patterns[] = "/<{\/if}>/";

		$replacements[] = '<?php foreach($$1 as $$3=>$$2):?>';
		$replacements[] = '<?php foreach($$1 as $$2):?>';
		$replacements[] = "<?php endforeach; ?>";
		$replacements[] = "<?php if $1: ?>";
		$replacements[] = "<?php elseif $1: ?>";
		$replacements[] = "<?php else: ?>";
		$replacements[] = "<?php endif; ?>";

		preg_match_all ('/<{include file="(.*?)"}>/',$contents,$out);
		if(count($out[0])>0){
			foreach($out[1] as $kv=>$v){
				$view = $this->tplpath.$v;
				$newname = md5($view).'.php';
				$patterns[] = '/'.str_replace('/', '\/', $out[0][$kv]).'/';
				$replacements[] = '<{include file="'.$newname.'"}>';
			}
		}
		
		$patterns[] = '/<{include file="(.*?)"}>/';
		$replacements[] = '<?php include("'.APPDATA.'cache/tpl/$1"); ?>';

		
		if($this->tpl_tag_cnf){
			$tagarr = $this->tpl_tag_cnf;
			foreach($tagarr as $v){
				preg_match_all('/<'.$v.'(.*)>/isU',$contents,$a);
				if(count($a[0])>0){
					foreach($a[0] as $m){
						$loc = str_replace(array('$','[',']'),array('\$','\[','\]'),'/'.$m.'/');
						$tar = '<?php $gfdata=array(';
						preg_match_all('/\s+(.*)="(.*)"/U',$loc,$b);
						if(count($b[1])>0){
							foreach($b[1] as $k=>$n){
								$fh = ',';
								if($k<1) $fh = '';
								$y = str_replace("\\","",$b[2][$k]);
								if (stripos($y, '$') !== false) $y = '".'.$y.'."';
								$tar .= $fh.'"'.$n.'"=>"'.$y.'"';
							}
						}
						$tar .= "); ?>\n";
						$tar .= '<?php foreach($tpl_tag->'.$v.'($gfdata) as $k=>$g):?>'."\n";
						$patterns[] = $loc;
						$replacements[] = $tar;
						$patterns[] = "/<\/{$v}>/";
						$replacements[] = '<?php endforeach; ?>';
					}

				}
			}
		}
		
		$patterns[] = "/<{(.*?)}>/";
		$replacements[] = "<?php echo $1; ?>";
		$contents = preg_replace($patterns, $replacements, $contents);

		$fp = fopen($newfilename,"w");	
		flock($fp, LOCK_EX) ;
		fwrite($fp,$contents);
		flock($fp, LOCK_UN); 
		fclose($fp);
		return $newfilename;
	}

} 